// miniprogram/pages/camera/camera.js
let garbageData = ""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //识别列表的显示
    isShow:false,
    garbageList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.cloud.callFunction({
      name:'baiduAccessToken'
    })
    .then((res) => {
      // console.log(res);
      this.access_token = res.result.access_token
    })
    .catch((err) => {
      wx.showToast({
        title: '获取access_token失败',
        icon:'none'
      })
    }) 
  },
  //调用wxApi，调起设备的摄像头
  takePhoto(){
    
    this.data.CameraContext = wx.createCameraContext()
    // console.log(CameraContext);
    this.data.CameraContext.takePhoto({
      quality:'high',
      success:(res) => {
        console.log(res);
        wx.showLoading({
          title: '识别中...',
        })
        // this.recognition(res.tempImagePath)
        //读取本地文件内容，将图片转为Base64格式
        wx.getFileSystemManager().readFile({
          filePath:res.tempImagePath,
          encoding:'base64',
          success:(res) => {
            console.log(res);
            this.recognition(res.data)
          },
          fail:(err) => {
            wx.hideLoading()
            wx.showToast({
              title:'拍照失败，未能获取拍照权限或其他原因',
              icon:'none'
            })
          }
        })
      }
    })
  },
  //调用百度ai接口，识别图片中的物品
  recognition(imgBase64){
    wx.request({
      url: `https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=${this.access_token}`,
      method:'post',
      data:{
        image: imgBase64
      },
      header:{
        'Content-Type':'application/x-www-form-urlencoded'
      },
      success:(res) => {
        let garbageItem = []
        console.log(res)
        if(res.data.result){
          // console.log(res.result)
          wx.showToast({
            title: '(识别成功)',
          })
          res.data.result.forEach((item) => {
            this.init(item.keyword).then((res) => {
              if(res[0]){
                garbageItem.push(res[0])
                this.setData({
                  garbageList:garbageItem,
                  isShow:true
                })
              }
            })
          })
            
        }else{
          wx.showToast({
            icon: 'none',
            title: '没有认出来，可以再试试~',
          })
        }
      },
      fail:(err) => {
        wx.showToast({
          icon: 'none',
          title: '请求失败了，请确保网络正常，重新试试~',
        })
      },
      complete:() => {
        wx.hideLoading();
      }
    })
  },
  //遍历垃圾数据
  async init(text){
    let res = await wx.cloud.callFunction({
      name:'getGarbageSort'
    })
    // console.log(res);
    let searchResult = new Array(),categoryName = "",categoryColor = ""
    garbageData = res.result
    garbageData.forEach((categoryItem) => {
      if(categoryItem && categoryItem.data && categoryItem.data.length > 0){
        // console.log(categoryItem);
        categoryItem.data.forEach((letterItem) => {
          let garbageItem = letterItem.garbageItem
          garbageItem.forEach((item) => {
            if(item == text){
              if(categoryItem.category == 1){
                categoryName = '可回收垃圾'
                categoryColor = '#014782'
              }else if(categoryItem.category == 2){
                categoryName = '有害垃圾'
                categoryColor = '#FF4500'
              }else if(categoryItem.category == 4){
                categoryName = '湿垃圾'
                categoryColor = '#664035'
              }else if(categoryItem.category == 8){
                categoryName = '干垃圾'
                categoryColor = '#2c2b27'
              }
              searchResult.push({
                categoryName,
                categoryColor,
                garbageItem:item,
              })
            }
          })
        })
      }
    })
    return searchResult
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})